#! -*- coding:utf-8 -*-
import json
import logging

from django.core.management.base import BaseCommand

from async import async_job
from common.channel import admin_db as channel_db
from common.channel.channel_map import CHANNEL_HANDLER
from common.order import admin_db as order_db
from common.order.model import PAY_STATUS

_LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):

    def handle(self, order_id_list, **options):
        for order_id in order_id_list.split(','):
            order_id = int(order_id)
            order = order_db.get_order(id=order_id)
            print 'merchant order id: %s' % order.out_trade_no
            async_job.notify_mch.delay(order_id)
            if order.status == 1:
                order.status = PAY_STATUS.READY
                order.save()
                chn = channel_db.get_channel(order.channel_id)
                chn_info = json.loads(chn.info)
                app_id = chn_info.get('app_id')
                chn_handler = CHANNEL_HANDLER[order.channel_type]
                chn_handler.query_charge(order, app_id)
